// 从后面开始删除，时间复杂度是O(n^2)
var removeDuplicates = function (nums) {
  let len = nums.length;
  let k = len - 1;
  for (let i = len - 2; i >= 0; i--) {
    if (nums[i] === nums[k] && k - i !== 1) {
      nums.splice(k, 1);
      k--;
    } else if (nums[i] === nums[k]) {
    } else {
      k = i;
    }
  }

  return nums.length;
};

// 使用快慢指针的方式，多一个变量来保存距离
/**
 * @param {number[]} nums
 * @return {number}
 */
var removeDuplicates = function (nums) {
  let slow = 0;
  let count = 0;
  for (let fast = 0; fast < nums.length; fast++) {
    if (fast > 0 && nums[fast] === nums[fast - 1]) {
      count++;
    } else {
      count = 1;
    }
    if (count <= 2) {
      nums[slow] = nums[fast];
      slow++;
    }
  }
  return slow;
};

let nums = [1, 1, 1];

console.log(removeDuplicates(nums));
